<?php

namespace App\Http\Controllers;

use App\Models\SystemLog;
use App\Services\LogService;
use App\Http\Controllers\Api\BaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * 日志管理控制器
 * 提供日志查询、管理和统计功能
 */
class LogController extends Controller
{
    public function __construct(
        private LogService $logService
    ) {}

    /**
     * 获取日志列表
     */
    public function index(Request $request): JsonResponse
    {
        $request->validate([
            'page' => 'integer|min:1',
            'per_page' => 'integer|min:1|max:100',
            'user_id' => 'integer',
            'module' => 'string',
            'level' => 'string|in:emergency,alert,critical,error,warning,notice,info,debug',
            'operation_type' => 'string',
            'date_from' => 'date',
            'date_to' => 'date',
            'sort_by' => 'string|in:created_at,id',
            'sort_order' => 'string|in:asc,desc',
        ]);

        try {
            $query = SystemLog::with('user')
                ->orderBy($request->input('sort_by', 'created_at'), $request->input('sort_order', 'desc'));

            // 应用过滤条件
            if ($request->has('user_id')) {
                $query->where('user_id', $request->input('user_id'));
            }

            if ($request->has('module')) {
                $query->where('module', $request->input('module'));
            }

            if ($request->has('level')) {
                $query->where('level', $request->input('level'));
            }

            if ($request->has('operation_type')) {
                $query->where('operation_type', $request->input('operation_type'));
            }

            if ($request->has('date_from') && $request->has('date_to')) {
                $query->whereBetween('created_at', [
                    $request->input('date_from') . ' 00:00:00',
                    $request->input('date_to') . ' 23:59:59'
                ]);
            }

            $perPage = $request->input('per_page', 20);
            $logs = $query->paginate($perPage);

            return $this->paginate($logs, '日志列表获取成功');
        } catch (\Exception $e) {
            Log::error('获取日志列表失败', ['error' => $e->getMessage()]);

            return $this->error('日志列表获取失败', 500);
        }
    }

    /**
     * 获取日志详情
     */
    public function show(string $id): JsonResponse
    {
        try {
            $log = SystemLog::with('user')->findOrFail((int)$id);

            return $this->success($log, '日志详情获取成功');
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('日志不存在', 404);
        } catch (\Exception $e) {
            Log::error('获取日志详情失败', ['id' => $id, 'error' => $e->getMessage()]);

            return $this->error('日志详情获取失败', 500);
        }
    }

    /**
     * 删除日志
     */
    public function destroy(string $id): JsonResponse
    {
        try {
            $log = SystemLog::findOrFail((int)$id);
            $log->delete();

            return $this->success(null, '日志删除成功');
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('日志不存在', 404);
        } catch (\Exception $e) {
            Log::error('删除日志失败', ['id' => $id, 'error' => $e->getMessage()]);

            return $this->error('日志删除失败', 500);
        }
    }

    /**
     * 批量删除日志
     */
    public function batchDestroy(Request $request): JsonResponse
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer'
        ]);

        try {
            $ids = $request->input('ids');
            $deletedCount = SystemLog::whereIn('id', $ids)->delete();

            return $this->success(['deleted_count' => $deletedCount], "成功删除 {$deletedCount} 条日志");
        } catch (\Exception $e) {
            Log::error('批量删除日志失败', ['error' => $e->getMessage()]);

            return $this->error('批量删除日志失败', 500);
        }
    }

    /**
     * 获取日志统计信息
     */
    public function statistics(Request $request): JsonResponse
    {
        $request->validate([
            'user_id' => 'integer',
            'module' => 'string',
            'level' => 'string',
            'date_from' => 'date',
            'date_to' => 'date',
        ]);

        try {
            $filters = array_filter([
                'user_id' => $request->input('user_id'),
                'module' => $request->input('module'),
                'level' => $request->input('level'),
                'date_from' => $request->input('date_from'),
                'date_to' => $request->input('date_to'),
            ]);

            $stats = $this->logService->getStatistics($filters);

            return $this->success($stats, '日志统计信息获取成功');
        } catch (\Exception $e) {
            Log::error('获取日志统计信息失败', ['error' => $e->getMessage()]);

            return $this->error('日志统计信息获取失败', 500);
        }
    }

    /**
     * 导出日志
     */
    public function export(Request $request): JsonResponse
    {
        $request->validate([
            'user_id' => 'integer',
            'module' => 'string',
            'level' => 'string',
            'date_from' => 'date',
            'date_to' => 'date',
            'format' => 'string|in:csv,json',
        ]);

        try {
            $filters = array_filter([
                'user_id' => $request->input('user_id'),
                'module' => $request->input('module'),
                'level' => $request->input('level'),
                'date_from' => $request->input('date_from'),
                'date_to' => $request->input('date_to'),
            ]);

            $format = $request->input('format', 'csv');
            $exportData = $this->logService->exportLogs($filters, $format);

            $filename = 'logs_' . now()->format('Y-m-d_H-i-s') . '.' . $format;

            return $this->success([
                'filename' => $filename,
                'content' => base64_encode($exportData),
                'format' => $format,
            ], '日志导出成功');
        } catch (\Exception $e) {
            Log::error('导出日志失败', ['error' => $e->getMessage()]);

            return $this->error('日志导出失败', 500);
        }
    }

    /**
     * 清理过期日志
     */
    public function cleanup(Request $request): JsonResponse
    {
        $request->validate([
            'days_to_keep' => 'integer|min:1|max:365',
        ]);

        try {
            $daysToKeep = $request->input('days_to_keep', 90);
            $deletedCount = $this->logService->cleanupLogs($daysToKeep);

            return $this->success(['deleted_count' => $deletedCount], "成功清理 {$deletedCount} 条过期日志");
        } catch (\Exception $e) {
            Log::error('清理过期日志失败', ['error' => $e->getMessage()]);

            return $this->error('清理过期日志失败', 500);
        }
    }

    /**
     * 获取日志模块列表
     */
    public function getModules(): JsonResponse
    {
        try {
            $modules = SystemLog::distinct('module')
                ->pluck('module')
                ->filter()
                ->values()
                ->toArray();

            return $this->success($modules, '日志模块列表获取成功');
        } catch (\Exception $e) {
            Log::error('获取日志模块列表失败', ['error' => $e->getMessage()]);

            return $this->error('日志模块列表获取失败', 500);
        }
    }

    /**
     * 获取日志级别列表
     */
    public function getLevels(): JsonResponse
    {
        $levels = [
            'emergency' => '紧急',
            'alert' => '警报',
            'critical' => '严重',
            'error' => '错误',
            'warning' => '警告',
            'notice' => '注意',
            'info' => '信息',
            'debug' => '调试',
        ];

        return $this->success($levels, '日志级别列表获取成功');
    }

    /**
     * 获取操作类型列表
     */
    public function getOperationTypes(): JsonResponse
    {
        try {
            $operationTypes = SystemLog::distinct('operation_type')
                ->pluck('operation_type')
                ->filter()
                ->values()
                ->toArray();

            return $this->success($operationTypes, '操作类型列表获取成功');
        } catch (\Exception $e) {
            Log::error('获取操作类型列表失败', ['error' => $e->getMessage()]);

            return $this->error('操作类型列表获取失败', 500);
        }
    }
}
